﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace HungryCrowdLibrary.Data
{
    internal class LocationData
    {
        internal Location GetDetail(int locationId)
        {
            var location = new Location();
            var locations = new List<Location>();
            var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HungryCrowd"].ConnectionString);
            conn.Open();

            using (var cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT * FROM dbo.Locations WHERE IsActive = 1 AND Id = @Id";
                cmd.Parameters.AddWithValue("@Id", locationId);
                cmd.Connection = conn;

                var reader = cmd.ExecuteReader();

                if (reader != null)
                    while (reader.Read())
                        location = LoadFromReader(reader);
            }
            return location;
        }

        internal List<Location> GetList()
        {
            var locations = new List<Location>();
            var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HungryCrowd"].ConnectionString);
            conn.Open();

            using (var cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT * FROM dbo.Locations WHERE IsActive = 1";
                cmd.Connection = conn;

                var reader = cmd.ExecuteReader();

                if (reader != null)
                    while (reader.Read())
                        locations.Add(LoadFromReader(reader));
            }
            return locations;
        }

        internal Location LoadFromReader(IDataReader reader)
        {
            var location = new Location();
            location.Markets = new List<Market>();

            location.Name = !string.IsNullOrWhiteSpace(reader["Name"].ToString()) ? reader["Name"].ToString() : string.Empty;
            location.Id = !string.IsNullOrWhiteSpace(reader["Id"].ToString()) ? int.Parse(reader["Id"].ToString()): 0;
            location.IsActive = !string.IsNullOrWhiteSpace(reader["IsActive"].ToString()) ? bool.Parse(reader["IsActive"].ToString()): false;
            location.Markets =  API.MarketManager.GetList(x=> x.LocationId == location.Id);

            return location;
        }

    }
}
